package com.servlet;

import com.dao.GoodsDAO;
import com.model.Goods;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

@WebServlet("/addGoods")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
        maxFileSize = 1024 * 1024 * 10, // 10MB
        maxRequestSize = 1024 * 1024 * 50) // 50MB
public class AddGoodsServlet extends HttpServlet {
    private static final String UPLOAD_DIR = "uploads";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        double price = Double.parseDouble(request.getParameter("price"));
        Part filePart = request.getPart("image");

        String imagePath = saveFile(filePart);
        String mark = request.getParameter("mark");
        double quantity = Integer.parseInt(request.getParameter("quantity"));

        Goods goods = new Goods();
        goods.setId(Integer.parseInt(id));
        goods.setName(name);
        goods.setPrice(price);
        goods.setImagePath(imagePath);
        goods.setMark(mark);
        goods.setQuantity(quantity);

        GoodsDAO goodsDAO = new GoodsDAO();
        goodsDAO.addGoods(goods);
        if ( goods!=null){
            response.sendRedirect("listGoods.jsp");
        } else {
            response.sendRedirect("error.jsp");
        }
        }



    private String saveFile(Part filePart) throws IOException {
        String fileName = extractFileName(filePart);
        String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIR;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        String filePath = uploadPath + File.separator + fileName;
        filePart.write(filePath);

        return UPLOAD_DIR + File.separator + fileName;
    }

    private String extractFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        String[] items = contentDisposition.split(";");
        for (String item : items) {
            if (item.trim().startsWith("filename")) {
                return item.substring(item.indexOf("=") + 2, item.length() - 1);
            }
        }
        return "";
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("addGoods.jsp");
    }
}
